<template>
  <!-- 广告组创建 -->
  <div>
    <!-- 账号 -->
    <div class="batch-block">
      <a-form-model
        ref="ruleForm"
        :model="accountForm"
        :label-col="{ span: 2 }"
        :rules="accountRules"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-model-item label="创建类型"  prop="accountType">
          <a-radio-group v-model="accountForm.accountType" button-style="solid">
            <a-radio-button value="odd"> 单账号 </a-radio-button>
            <a-radio-button value="double">  跨账号 </a-radio-button>
          </a-radio-group>
        </a-form-model-item>

        <a-form-model-item v-if="accountForm.accountType === 'odd'" label="广告投放账号" prop="accountIdOdd">
          <a-select showSearch v-model="accountForm.accountIdOdd" @change="getCampaign" :filterOption="filterOption">
            <a-select-option
              v-for="item in account"
              :key="item.name"
              :value="item.account_id"
            >
              {{ `${item.name} ( ${item.account_id} ) ` }}
            </a-select-option>
          </a-select>
        </a-form-model-item>

        <a-form-model-item v-if="accountForm.accountType === 'double'" label="广告投放账号">
          <div style="width:100%;">
            <div style="margin-bottom: 16px">
              <span style="margin-right:10px;">{{ `已选 ${accountForm.DoubelRowKeys.length} 账户` }}</span>
              <span><a-icon type="close" @click="closeAccountDouble" class="closeAccountDouble" title="清除所有已选账号!!!" /></span>
            </div>
            <a-input-search placeholder="筛选账号" v-model="queryParam.keyWord" enter-button @search="getAccount" />
            <a-table
              size="small"
              :row-selection="{ selectedRowKeys:accountForm.DoubelRowKeys,onSelect:onSelectDouble,columnTitle:' '  }"
              :columns="columns"
              :data-source="account"
              rowKey='account_id'
            >
              <template slot="name" slot-scope="text,row">
                <span>{{ `${row.name} ( ${row.account_id} ) ` }}</span>
              </template>
            </a-table>
          </div>
        </a-form-model-item>
      </a-form-model>
    </div>
    <!-- 广告组 -->
    <div class="batch-block">
      <a-form-model
        ref="ruleForms"
        :model="campaignForm"
        :label-col="{ span: 2 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-model-item label="广告组推广类型"  prop="landingType">
          <a-radio-group
            v-model="campaignForm.landing_type"
            button-style="solid"
            @change="getCampaign"
          >
            <a-radio-button value="APP"> 应用推广 </a-radio-button>
            <a-radio-button value="LINK"> 销售线索收集 </a-radio-button>
          </a-radio-group>
        </a-form-model-item>

        <a-form-model-item v-if="accountForm.accountType === 'double'" prop="accountIdOdd">
          <double-campaign
            :selectedAccount="accountForm.accountIdDoubel"
            :doubelRowKeys="accountForm.DoubelRowKeys"
            :selectedCampaigns="campaignForm.selectedCampaigns"
            :selectedCampaignsObj.sync="campaignForm.campaignSelectedObjDouble"
            :landingType="campaignForm.landing_type"
          ></double-campaign>
        </a-form-model-item>

        <a-form-model-item v-if="accountForm.accountType === 'odd'" label="广告组">
          <div style="width:100%;">
            <a-table
              size="small"
              :row-selection="{ selectedRowKeys:campaignForm.campaignSelected,onSelect:onSelectOdd,columnTitle:' ' }"
              :columns="campaignColumns"
              rowKey='id'
              :data-source="campaignOdd"
            />
          </div>
        </a-form-model-item>
      </a-form-model>
    </div>

    <div class="next">
      <a-button type="primary" @click="next">
        下一步
      </a-button>
    </div>
  </div>
</template>

<script>
import { getAccountListGet } from "@/api/adv/account";
import { getCampaignListGet } from "@/api/adv/campaign";

export default {
  components:{ 
    'doubleCampaign':()=>import('../components/doubleCampaign')
  },
  data() {
    return {
      columns:[{ title:'账号',scopedSlots: {customRender:'name'} } ], // table
      campaignColumns:[ { title: '列表', dataIndex:'name' } ], // table
      // 账户
      accountForm: {
        accountType:'double',
        accountIdOdd:'',  // 单账号
        accountIdDoubel:[],  //跨账号 已选账号 {}  且 广告组账号
        DoubelRowKeys: [], // 跨账号 已选账号 string
      },
      // 广告组
      campaignForm: {
        landing_type:'APP',
        campaignSelected:[],  //已选广告组 [id] odd
        campaignSelectedOdd:[],  //已选广告组 [{}]  odd
        selectedCampaigns:[],   //已选广告组 [id] double
        campaignSelectedObjDouble:[],  //已选广告组 [{}]  double
      },
      account:[], // 账号数据
      campaignOdd:[],  //广告组 数据   (单选账号)
      // selectedAccount:[], // 已选账号 double {}
      accountRules:{
        accountType: [{ required: true, message: '选择创建类型', trigger: 'change' }],
        accountIdOdd: [{ required: true, message: '选择账户', trigger: 'change' }],
      },
      // 跨账号筛选条件
      queryParam:{
        status:'ENABLE',
        keyWord:''
      },
    }
  },
  watch:{
    campaignForm:{
      deep:true,
      immediate:true,
      handler(params,olddata){
        if( params.campaignSelected.length !== 0 && this.campaignOdd.length === 0  ){
          this.getCampaign()
        }
      }
    },
    'campaignForm.landing_type':function (params) {
      if( this.accountForm.accountType === 'double' ) return
      this.campaignForm.campaignSelected = []
      this.campaignForm.campaignSelectedOdd = []
    }
  },
  created(){
    this.getAccount()
  },
  mounted(){
    if( Object.keys(this.$route.query).length !== 0 ){
      this.accountForm = Object.assign( this.accountForm,JSON.parse(this.$route.query.data).accountForm ) 
      this.campaignForm = Object.assign( this.campaignForm,JSON.parse(this.$route.query.data).campaignForm )
    }
  },
  methods: {
    // a-select 自定义搜索（label）
    filterOption(input, option){
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
    // 获取账号
    getAccount(){
      getAccountListGet(this.queryParam).then((res)=>{
        this.account = res.data
      })
    },
    // 获取广告组 odd (选择账号时，清空广告组)
    getCampaign(){
      if( this.accountForm.accountIdOdd ){
        this.campaignForm.campaignSelectedOdd = []
        this.campaignForm.campaignSelected = []
        let quert = { 
          account_id:this.accountForm.accountIdOdd,
          landing_type:this.campaignForm.landing_type,
          status:'CAMPAIGN_STATUS_ENABLE'
        }
        getCampaignListGet(quert).then((res)=>{
          this.campaignOdd = res.data
        })
      }
    },
    // table 选择账号 double
    onSelectDouble(item,is_check){
      if(is_check){
        this.accountForm.DoubelRowKeys.push( item.account_id )
        this.accountForm.accountIdDoubel.push(item)
      }else {
        let index = this.accountForm.DoubelRowKeys.indexOf( item.account_id )
        this.accountForm.DoubelRowKeys.splice(index,1)
        this.accountForm.accountIdDoubel.splice(index,1)
      }
    },
    closeAccountDouble(){
      if( this.accountForm.DoubelRowKeys.length === 0 ) return this.$Tip('请先选择账号!!') 
      this.accountForm.accountIdDoubel = []
      this.accountForm.DoubelRowKeys = []

      this.campaignForm.selectedCampaigns = []
      this.campaignForm.campaignSelectedObjDouble = []
    },
    // 选择广告组 [{}] odd
    onSelectOdd(item,checked){
      if(checked){
        this.campaignForm.campaignSelected.push( item.id )
        this.campaignForm.campaignSelectedOdd.push(item)
      }else {
        this.campaignForm.campaignSelected.splice( this.campaignForm.campaignSelectedOdd.indexOf(item),1 )
        this.campaignForm.campaignSelectedOdd.splice(this.campaignForm.campaignSelectedOdd.indexOf(item),1)
      }
    },
    // 下一步  vuex储存   账号、广告组(数组对象)
    next(){
      // console.info(this.accountForm,this.campaignForm,'accountForm')
      let campaign = { account_id:[], campaign_id:null,landing_type:this.campaignForm.landing_type }
      if( this.accountForm.accountType === 'odd' ){
        if(this.campaignForm.campaignSelectedOdd.length === 0) return alert('请选择广告组')
        // 遍历账号，获取与选择的账号account_id相同的账号数据
        for (let i = 0; i < this.account.length; i++) {
          if( this.account[i].account_id === this.accountForm.accountIdOdd ){
            campaign.account_id.push(this.account[i])
            break;
          } 
        }
        campaign.campaign_id = this.campaignForm.campaignSelectedOdd
      }else {
        if(this.campaignForm.campaignSelectedObjDouble.length === 0) return alert('请选择广告组')
        let campaign_account_ids = []
        // 筛选已选广告组，获取用户账号
        for (const campaign of this.campaignForm.campaignSelectedObjDouble) {
          if( campaign_account_ids.indexOf(campaign.account_id) === -1 ) campaign_account_ids.push(campaign.account_id)
        }
        // 遍历已选账号，判断是否有已选广告组账号，如果没有，那这个账号没有选广告组
        for (const account of this.accountForm.accountIdDoubel) {
          if( !campaign_account_ids.includes(account.account_id) ) return alert(`${ account.name }请选择广告组`)
        }
        campaign.account_id = this.accountForm.accountIdDoubel
        campaign.campaign_id = this.campaignForm.campaignSelectedObjDouble
      }
      localStorage.setItem('campaign',JSON.stringify(campaign))
      this.$store.commit('SET_ECHO_VIEW_ACCOUNT_ID',this.accountForm)
      this.$store.commit('SET_ECHO_VIEW_CAMPAIGN',this.campaignForm)
      this.$store.commit('SET_CAMPAIGNS',campaign ); // vuex储存数据
      this.$emit('nexts')
    }
  },
}
</script>
 <style lang="less" scoped>
  .closeAccountDouble:hover{
    cursor: pointer;
    color: red;
  }
 </style>